package com.leo.ibatis.demo.dao.ibatis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.LineitemCriteria;
import com.leo.ibatis.demo.dao.LineitemDao;
import com.leo.ibatis.demo.domain.Lineitem;
import com.leo.ibatis.demo.util.Paging;

public class LineitemDaoImpl extends SqlMapClientDaoSupport implements LineitemDao {

	public void insert(Lineitem lineitem) throws DataAccessException {
		getSqlMapClientTemplate().insert("Lineitem.insert", lineitem);
	}

	public int update(Lineitem lineitem) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Lineitem.update", lineitem, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(int linenum, int orderid) throws DataAccessException {
		int actualRowsAffected = 1;

		Map<String, Object> param = new HashMap<String, Object>(2);
		param.put("linenum", new Integer(linenum));
		param.put("orderid", new Integer(orderid));

		getSqlMapClientTemplate().delete("Lineitem.delete", param, actualRowsAffected);

		return actualRowsAffected;
	}

	public Lineitem select(int linenum, int orderid) throws DataAccessException {
		Map<String, Object> param = new HashMap<String, Object>(2);
		param.put("linenum", new Integer(linenum));
		param.put("orderid", new Integer(orderid));

		return (Lineitem) getSqlMapClientTemplate().queryForObject("Lineitem.select", param);
	}

	@SuppressWarnings("unchecked")
	public List<Lineitem> list(LineitemCriteria lineitemCriteria) throws DataAccessException {
		Assert.notNull(lineitemCriteria, "lineitemCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Lineitem.list", lineitemCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Lineitem> listOnPage(LineitemCriteria lineitemCriteria) throws DataAccessException {
		Assert.notNull(lineitemCriteria, "lineitemCriteria must not be null");
		Assert.notNull(lineitemCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(lineitemCriteria);
		Paging paging = lineitemCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Lineitem.list", lineitemCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(LineitemCriteria lineitemCriteria) throws DataAccessException {
		Assert.notNull(lineitemCriteria, "lineitemCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Lineitem.count", lineitemCriteria)).intValue();
	}

}
